package com.minggo.charmword.service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.Buffer;
import java.util.Stack;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.platform.comapi.map.o;
import com.minggo.charmword.R;
import com.minggo.charmword.model.User;
import com.minggo.charmword.util.UserUtil;

/**
 * 应用全局
 * 
 * @author minggo
 * @time 2014-6-23 S下午10:49:54
 */
public class CharmWordApplication extends Application {

	public static final String EMAIL = "minggo8en@gmail.com";
	public static Stack<Activity> allActivities;
	public static final String TAOBAO_URL = "http://bang.taobao.com/item.htm?id=40301430368&spm=686.1000925.1000774.14.yJvphM&mt=";
	public static String SDPATH = Environment.getExternalStorageDirectory().getPath() + "/minggo.charmword/";// 主程序SD卡目录
	private static CharmWordApplication charmWordApplication;

	public User user;
	private LocationClient mLocClient;
	public BDLocation mbdLocation;

	@Override
	public void onCreate() {
		super.onCreate();
		//copyDatabase();
		allActivities = new Stack<Activity>();

		firstInit();
		SDKInitializer.initialize(this);
		charmWordApplication = this;
		location();
	}

	/**
	 * 拷贝数据库
	 */
	private void copyDatabase() {
		String DB_PATH = this.getFilesDir().getPath() + "/databases/";
		String DB_NAME = "charmword.db";
		byte[] encryptedKey = "minggo620".getBytes();
		File dfile = new File(DB_PATH, DB_NAME);
		if (!dfile.exists()) {
			createDir(new String[] { "/databases"});
			InputStream inputStream = null;
			FileOutputStream outputStream = null;
			try {
				inputStream = getResources().openRawResource(R.raw.charmword);
				if (inputStream != null) {
					outputStream = new FileOutputStream(dfile);
					byte[] buffer = new byte[1024];
					int count = 0;
					int  pos, keylen;
					pos = 0;
					keylen = encryptedKey.length;
					while ((count = inputStream.read(buffer)) > 0) {
						for (int i = 0; i < count; i++) {
							buffer[i] ^= encryptedKey[pos];
							outputStream.write(buffer[i]);
							pos++;
							if (pos == keylen)
								pos = 0;
						}
						//outputStream.write(buffer, 0, count);
					}
					outputStream.flush();
				}

			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (outputStream != null) {
						outputStream.close();
						outputStream = null;
					}
					if (inputStream != null) {
						inputStream.close();
						inputStream = null;
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}

	}

	/**
	 * 
	 */
	public void createDir(String dirs[]) {
		File dir;
		for (String string : dirs) {
			dir = new File(this.getFilesDir().getPath() + string);
			if (!dir.exists()) {
				dir.mkdir();
			}
		}
	}

	public static CharmWordApplication getInstance() {
		return charmWordApplication;
	}

	/**
	 * 定位
	 */
	private void location() {
		// 定位初始化
		mLocClient = new LocationClient(this.getApplicationContext());
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setScanSpan(30000);
		option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
		option.setIsNeedAddress(true);
		mLocClient.registerLocationListener(new BDLocationListener() {

			@Override
			public void onReceiveLocation(BDLocation bdLocation) {
				mbdLocation = bdLocation;
				mLocClient.unRegisterLocationListener(this);
				mLocClient.stop();
			}
		});
		mLocClient.setLocOption(option);
		mLocClient.start();
	}

	/**
	 * 结束所有Activity
	 */
	public static void finishAllActivity() {
		for (int i = 0, size = allActivities.size(); i < size; i++) {
			if (null != allActivities.get(i)) {
				allActivities.get(i).finish();
			}
		}
		allActivities.clear();
	}

	/**
	 * 推出应用
	 */
	public void stopAPP() {
		finishAllActivity();
		this.stopService(new Intent("minggo.battery.alarm.service"));
		android.os.Process.killProcess(android.os.Process.myPid());
		System.exit(0);
	}

	/**
	 * 第一次安装时的初始化
	 */
	private void firstInit() {
		boolean preferences = getSharedPreferences("first", Context.MODE_PRIVATE).getBoolean("isfrist", true);
		if (preferences) {
			User user = new User();
			user.username = "sys_minggo";
			user.email = EMAIL;
			user.password = "12345678";
			user.type = 0;
			UserUtil.saveUser(this, user);
		}
	}

}
